<?php

namespace App\Console\Commands;

use App\Library\Logic\AuctionBailLogic;
use App\Library\Logic\AuctionLogic;
use App\Library\Logic\AuctionOrderLogic;
use App\Library\YsdLib;
use Exception;
use Illuminate\Console\Command;
use Yansongda\Pay\Pay;

class AuctionBailRefundCommand extends Command
{
    /**
     * 退拍卖保释金金额
     *
     * @var string
     */
    protected $signature = 'command:auctionBailRefund {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $order = AuctionBailLogic::query()->where(humpToLine([
            'serial_number' => $serialNumber,
            'status' => 2,
            'status_pay' => 1,
        ]))->whereNotNull('pay_at')->first();
        if (is_null($order)) return;
        else if (is_null($order->paymentRelated)) return;
        else if (is_null($order->payment)) return;
        $auction = AuctionLogic::detail($order->auction_id);
        if (is_null($auction)) return;
        else if ($auction->sell_out === 0 && $auction->expired === 0) return;
        $count = AuctionOrderLogic::query()->where(humpToLine([
            'auctionId' => $order->auction_id,
            'userId' => $order->user_id,
            'statusPay' => 0,
        ]))->whereNull('pay_at')->count();
        if ($count !== 0) return;
        $result = Pay::wechat(YsdLib::config())->refund([
            'transaction_id' => $order->payment->out_trade_no,
            'out_trade_no' => $order->paymentRelated->serial_number,
            'out_refund_no' => $order->serial_number,
            'reason' => '退款',
            'notify_url' => config('app.url') . 'wechat/auctionBailRefund',
            'amount' => [
                'refund' => prod() ? (int)bcmul($order->order_price, 100) : 1,
                'total' => prod() ? (int)bcmul($order->order_price, 100) : 1,
                'currency' => 'CNY',
            ],
        ]);
        $order->status_bail = 99;
        $order->save();
        payLog($result->toArray());
    }
}
